using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

using Utilities;

namespace GPX
{
    public partial class MapForm : FormEx
    {
        private TrackSegment _ActiveTrackSegment;
        private string[] _AcceptablePhotoTypes = { ".jpg", ".jpeg" };
        private TimeSpan _DefaultTimeDiffForPhotos;

        private System.Resources.ResourceManager ResourceManager
        {
            get { return GPXAppResourceManager.ResourceManager; }
        }

        private MapForm() { InitializeComponent(); }
        public MapForm(TrackSegment trackSegment)
        {
            InitializeComponent();
            //for some unknown reason, the trackControl often grows when the form is opened in the designer
            trackControl.Location = new System.Drawing.Point(0, 0);
            trackControl.Height = splitContainer1.Panel2.ClientSize.Height;
            trackControl.Width = splitContainer1.Panel2.ClientSize.Width;
            lvPhotos.LargeImageList = new ImageList();

            if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Runtime)
            {
                _ActiveTrackSegment = trackSegment;
                Localizer.LocalizeControl(this, ResourceManager);
            }
        }

        #region Properties
        private EditAxesDialog _EditAxesDialog;
        private EditViewDialog _EditViewDialog;

        private bool _UseEqualScale;
        internal bool UseEqualScale
        {
            get { return _UseEqualScale; }
            set { _UseEqualScale = value; }
        }

        private Single _Zoom;
        internal Single Zoom
        {
            get { return _Zoom; }
            set { _Zoom = value; }
        }

        private bool _UseMap;
        internal bool UseMap
        {
            get { return _UseMap; }
            set { _UseMap = value; }
        }

        private DrawCategory _XCategory;
        internal DrawCategory XCategory
        {
            get { return _XCategory; }
            set { _XCategory = value; }
        }

        private DrawCategory _YCategory;
        internal DrawCategory YCategory
        {
            get { return _YCategory; }
            set { _YCategory = value; }
        }

        private bool _ShowMap;
        internal bool ShowMap
        {
            get { return _ShowMap; }
            set { _ShowMap = value; }
        }

        private GMap.NET.MapType _MapType;
        [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        internal GMap.NET.MapType MapType
        {
            get { return _MapType; }
            set { _MapType = value; }
        }

        private bool _ShowAllPointsOfSegment;
        internal bool ShowAllPointsOfSegment
        {
            get { return _ShowAllPointsOfSegment; }
            set { _ShowAllPointsOfSegment = value; }
        }

        private int _IndexOfFirstPointShown;
        internal int IndexOfFirstPointShown
        {
            get { return _IndexOfFirstPointShown; }
            set { _IndexOfFirstPointShown = value; }
        }

        private int _IndexOfLastPointShown;
        internal int IndexOfLastPointShown
        {
            get { return _IndexOfLastPointShown; }
            set { _IndexOfLastPointShown = value; }
        }

        private bool _DrawWaypoints;
        internal bool DrawWaypoints
        {
            get { return _DrawWaypoints; }
            set { _DrawWaypoints = value; }
        }

        private bool _DrawTrackLine;
        internal bool DrawTrackLine
        {
            get { return _DrawTrackLine; }
            set { _DrawTrackLine = value; }
        }

        private bool _DrawPhotos;
        internal bool DrawPhotos
        {
            get { return _DrawPhotos; }
            set { _DrawPhotos = value; }
        }

        private bool _DrawPointsOfInterest;
        internal bool DrawPointsOfInterest
        {
            get { return _DrawPointsOfInterest; }
            set { _DrawPointsOfInterest = value; }
        }

        private WaypointsStyle _StyleForWaypoints;
        internal WaypointsStyle StyleForWaypoints
        {
            get { return _StyleForWaypoints; }
            set { _StyleForWaypoints = value; }
        }

        private WaypointsStyle _StyleForPoI;
        internal WaypointsStyle StyleForPoI
        {
            get { return _StyleForPoI; }
            set { _StyleForPoI = value; }
        }

        private float _TrackThickness;
        internal float TrackThickness
        {
            get { return _TrackThickness; }
            set { _TrackThickness = value; }
        }

        private PhotoSize _PhotoSize;
        [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        internal PhotoSize PhotoSize
        {
            get { return _PhotoSize; }
            set { _PhotoSize = value; }
        }

        private Color _WayPointsColor;
        internal Color WayPointsColor
        {
            get { return _WayPointsColor; }
            set { _WayPointsColor = value; }
        }

        private Color _WayPointsHighlight;
        internal Color WayPointsHighlight
        {
            get { return _WayPointsHighlight; }
            set { _WayPointsHighlight = value; }
        }

        private Color _PoIColor;
        internal Color PoIColor
        {
            get { return _PoIColor; }
            set { _PoIColor = value; }
        }

        private Color _TrackColor;
        internal Color TrackColor
        {
            get { return _TrackColor; }
            set { _TrackColor = value; }
        }

        private Color _TrackColorHighlight = Color.Goldenrod;
        internal Color TrackColorHighlight
        {
            get { return _TrackColorHighlight; }
            set { _TrackColorHighlight = value; }
        }

        private List<WayPoint> _PointsOfInterest;
        public List<WayPoint> PointsOfInterest
        {
            get { return _PointsOfInterest; }
            set { _PointsOfInterest = value; }
        }

        private DateTime _CacheDate;
        internal DateTime CacheDate
        {
            get { return _CacheDate; }
            set { _CacheDate = value; }
        }

        private int _LastSplitterPosition;
        #endregion Properties

        private void btnDraw_Click(object sender, EventArgs e)
        {
            Redraw();
        }
        private void Redraw()
        {
            try
            {
                if (trackControl.TrackSegmentShown == null)
                    trackControl.TrackSegmentShown = _ActiveTrackSegment;
                trackControl.SetPointsOfInterest(_PointsOfInterest);
                trackControl.CacheDate = _CacheDate;

                trackControl.UseEqualScale = _UseEqualScale;
                trackControl.Zoom = _Zoom;

                //how to show waypoints
                trackControl.DrawWaypoints = _DrawWaypoints;
                trackControl.StyleForWaypoints = _StyleForWaypoints;
                trackControl.WayPointsColor = _WayPointsColor;
                trackControl.WayPointsHighlight = _WayPointsHighlight;

                trackControl.DrawPointsOfInterest = _DrawPointsOfInterest;
                trackControl.StyleForPoI = _StyleForPoI;
                trackControl.PoIColor = _PoIColor;

                trackControl.DrawTrackLine = _DrawTrackLine;
                trackControl.TrackThickness = _TrackThickness;
                trackControl.TrackColor = _TrackColor;
                trackControl.TrackColorHighlight = _TrackColorHighlight;

                trackControl.DrawPhotos = _DrawPhotos;
                trackControl.PhotoSize = _PhotoSize;

                trackControl.ShowMap = _UseMap;
                if (!_UseMap)
                {
                    trackControl.XCategory = _XCategory;
                    trackControl.YCategory = _YCategory;
                }
                else
                {
                    //with Maps, it is always latitude/longitude to be used for further calculation!
                    trackControl.XCategory = DrawCategory.Longitude;
                    trackControl.YCategory = DrawCategory.Latitude;
                }

                //which points to show
                trackControl.ShowAllPointsOfSegment = _ShowAllPointsOfSegment;
                trackControl.IndexOfFirstPointShown = _IndexOfFirstPointShown;
                trackControl.IndexOfLastPointShown = _IndexOfLastPointShown;

                //show a map?
                trackControl.ShowMap = _ShowMap;
                trackControl.MapType = _MapType;

                trackControl.Draw();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                List<WayPoint> wps = trackControl.GetSelection();
                _ActiveTrackSegment.BeginUpdate();
                foreach (WayPoint wp in wps)
                {
                    _ActiveTrackSegment.DeleteWaypoint(wp);
                }
                _ActiveTrackSegment.EndUpdate();

                if (_IndexOfLastPointShown > _ActiveTrackSegment.WayPoints.Count)
                    _IndexOfLastPointShown = _ActiveTrackSegment.WayPoints.Count;

                trackControl.Draw();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void btnSaveAs_Click(object sender, EventArgs e)
        {
            try
            {
                List<WayPoint> wps = trackControl.GetSelection();
                TrackSegment seg = new TrackSegment();
                seg.WayPoints = wps;
                Track track = new Track();
                track.TrackSegments = new List<TrackSegment>();
                track.TrackSegments.Add(seg);
                track.Name = "Track #1";
                GPXType gpx = new GPXType();
                gpx.Creator = Defaults.GPXCreator; //"Bernie's GPX Tool";
                gpx.Tracks = new List<Track>();
                gpx.Tracks.Add(track);
                gpx.ToFile(Defaults.GPXSnippetLocation); //@"C:\Temp\Temp.gpx"
                //GPX_MapForm_SaveAsMsg=The snippet has been save to {0}.
                MessageBox.Show(string.Format(ResourceManager.GetString("GPX_MapForm_SaveAsMsg"), Defaults.GPXSnippetLocation));
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void MapForm_Load(object sender, EventArgs e)
        {
            try
            {
                trackControl.WayPointSelected += new TrackControl.WayPointSelectedEventHandler(trackControl_WayPointSelected);

                _XCategory = Defaults.TrackControl_X_Axis;
                _YCategory = Defaults.TrackControl_Y_Axis;

                _UseEqualScale = Defaults.TrackForm_EqualScales;
                _Zoom = 1.0f;

                _DrawWaypoints = true;
                _StyleForWaypoints = Defaults.TrackControl_WaypointsStyle;
                _WayPointsColor = Color.BlanchedAlmond;
                _WayPointsHighlight = Color.Gold;

                _DrawPointsOfInterest = true;
                _StyleForPoI = Defaults.TrackControl_PointsOfInterestStyle;
                _PoIColor = Color.DarkGreen;

                _ShowAllPointsOfSegment = true;
                _IndexOfFirstPointShown = 1;
                _IndexOfLastPointShown = _ActiveTrackSegment.WayPoints.Count;

                _ShowMap = Defaults.TrackControl_ShowMap;
                _UseMap = _ShowMap;
                _MapType = Defaults.TrackControl_MapType;

                _DrawTrackLine = true;
                _TrackThickness = 3.0f;
                _TrackColor = Color.Red;

                _DrawPhotos = true;
                _PhotoSize = PhotoSize.Small;

                _LastSplitterPosition = splitContainer1.SplitterDistance;

                _CacheDate = new DateTime(2000, 1, 1);

                this.WindowState = Defaults.TrackForm_Maximized ? FormWindowState.Maximized : FormWindowState.Normal;
                if (Defaults.TrackForm_AutoDraw)
                    Redraw();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void trackControl_WayPointSelected(object sender, WayPointSelectedEventArgs wpArgs)
        {
            try
            {
                //MessageBox.Show("Selected WayPoint: " + wpArgs.SelectedWaypoint.Index.ToString());
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void btnElevation_Click(object sender, EventArgs e)
        {
            try
            {
                //MessageBox.Show("Selected WayPoint: " + wpArgs.SelectedWaypoint.Index.ToString());
                ElevationAdjustmentForm eaf = new ElevationAdjustmentForm(_ActiveTrackSegment, trackControl);
                eaf.Show();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        #region Photos
        private void mnuMapAgain_Click(object sender, EventArgs e)
        {
            try
            {
                bool overwrite = false;
                bool askAgain = true;
                int remappedCount = 0;
                foreach (ListViewItem lvi in lvPhotos.SelectedItems)
                {
                    PhotoInfo pi = lvi.Tag as PhotoInfo;
                    if (pi.PreviouslyMapped && askAgain)
                    {
                        AskOverwriteDialog aoDLg = new AskOverwriteDialog();
                        aoDLg.PhotoInfo = pi;
                        DialogResult res = aoDLg.ShowDialog();
                        askAgain = !aoDLg.ApplyForAll;
                        overwrite = (res == DialogResult.Yes);
                    }
                    if (overwrite || !pi.PreviouslyMapped)
                    {
                        MapPhoto(pi);
                        remappedCount++;
                    }
                }
                if (remappedCount > 0)
                {
                    trackControl.Draw();
                }
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void MapPhoto(PhotoInfo pi)
        {
            bool mapped = false;
            foreach (WayPoint wp in _ActiveTrackSegment.WayPoints)
            {
                if (wp.Time > pi.GPSTime)
                {
                    if (wp.PreviousWaypoint == null)
                    {
                        //hm... set to this (first) Waypoint
                        pi.Latitude = new Degree((double)wp.Latitude, Direction.Latitude);
                        pi.Longitude = new Degree((double)wp.Longitude, Direction.Longitude);
                    }
                    else
                    {
                        //linear interpolation
                        WayPoint previous = wp.PreviousWaypoint;
                        TimeSpan deltaWaypoints = wp.Time - previous.Time;
                        TimeSpan deltaPhoto = pi.GPSTime - previous.Time;
                        double factor = ((double)deltaPhoto.Ticks / (double)deltaWaypoints.Ticks);
                        double latitude = (double)previous.Latitude + factor * ((double)wp.Latitude - (double)previous.Latitude);
                        double longitude = (double)previous.Longitude + factor * ((double)wp.Longitude - (double)previous.Longitude);
                        pi.Latitude = new Degree(latitude, Direction.Latitude);
                        pi.Longitude = new Degree(longitude, Direction.Longitude);
                    }
                    mapped = true;
                    break;
                }
            }
            if (!mapped)
            {
                //hm... set to last Waypoint
                WayPoint wp = _ActiveTrackSegment.LastWayPoint;
                pi.Latitude = new Degree((double)wp.Latitude, Direction.Latitude);
                pi.Longitude = new Degree((double)wp.Longitude, Direction.Longitude);
            }
        }

        private void mnuChangeTime_Click(object sender, EventArgs e)
        {
            try
            {
                //if (lvPhotos.SelectedItems.Count == 0)
                //{
                //    MessageBox.Show(ResourceManager.GetString("GPX_MapForm_NoSelection"));
                //    return;
                //}

                TimeDeltaDialog tdDlg = new TimeDeltaDialog();

                if (lvPhotos.SelectedItems.Count > 0)
                {
                    PhotoInfo pi = lvPhotos.SelectedItems[0].Tag as PhotoInfo;
                    tdDlg.SetPhotoTime(pi.PhotoTime);
                    tdDlg.SetGPSTime(pi.GPSTime);
                }

                if (tdDlg.ShowDialog() == DialogResult.OK)
                {
                    TimeSpan deltaT = tdDlg.SelectedTimeSpan;
                    foreach (ListViewItem lvi in lvPhotos.SelectedItems)
                    {
                        PhotoInfo pi = lvi.Tag as PhotoInfo;
                        pi.SetTimeDifference(deltaT);
                        MapPhoto(pi);
                    }

                    if (tdDlg.SetAsDefault)
                    {
                        _DefaultTimeDiffForPhotos = deltaT;
                    }

                    trackControl.Draw();
                }
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void MapForm_DragEnter(object sender, DragEventArgs e)
        {
            try
            {
                DragDropEffects effect = DragDropEffects.None;
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                    bool done = false;
                    foreach (string file in files)
                    {
                        string extension = System.IO.Path.GetExtension(file.ToLower());
                        foreach (string acceptableType in _AcceptablePhotoTypes)
                        {
                            if (acceptableType == extension)
                            {
                                effect = DragDropEffects.Copy;
                                done = true;
                                break;
                            }
                        }
                        if (done)
                            break;
                    }
                }
                e.Effect = effect;
            }
            catch
            {
                //swallow
            }
        }

        private void MapForm_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    int countAdded = 0;
                    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                    foreach (string file in files)
                    {
                        string extension = System.IO.Path.GetExtension(file.ToLower());
                        foreach (string acceptableType in _AcceptablePhotoTypes)
                        {
                            if (acceptableType == extension)
                            {
                                //check if already present
                                bool add = true;
                                foreach (ListViewItem lvi in lvPhotos.Items)
                                {
                                    string lvFileName = (lvi.Tag as PhotoInfo).FileName;
                                    if (file.ToLower() == lvFileName)
                                    {
                                        add = false;
                                        break;
                                    }
                                }

                                if (add)
                                {
                                    PhotoInfo pi = new PhotoInfo(file, _DefaultTimeDiffForPhotos);
                                    pi.ShowOnMap = true;
                                    if (!pi.PreviouslyMapped)
                                    {
                                        MapPhoto(pi);
                                    }
                                    ListViewItem lvi = new ListViewItem(pi.ToString());
                                    lvi.Tag = pi;
                                    lvPhotos.LargeImageList.Images.Add(pi.Icon);
                                    lvi.ImageIndex = lvPhotos.LargeImageList.Images.Count - 1;
                                    lvPhotos.Items.Add(lvi);
                                    trackControl.Photos.Add(pi);
                                    countAdded++;
                                }

                                break;
                            }
                        }
                    }
                    if (countAdded > 0)
                    {
                        lvPhotos.Refresh();
                        trackControl.Draw();
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void mnuClear_Click(object sender, EventArgs e)
        {
            try
            {
                lvPhotos.Items.Clear();
                lvPhotos.LargeImageList.Images.Clear();
                lvPhotos.Refresh();
                trackControl.Photos.Clear();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void mnuSave_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (ListViewItem lvi in lvPhotos.SelectedItems)
                {
                    PhotoInfo pi = lvi.Tag as PhotoInfo;
                    pi.Save();
                }
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void mnuSaveAs_Click(object sender, EventArgs e)
        {
            try
            {
                if (lvPhotos.SelectedItems.Count == 1)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        PhotoInfo pi = lvPhotos.SelectedItems[0].Tag as PhotoInfo;
                        pi.SaveAs(sfd.FileName);
                    }
                }
                else if (lvPhotos.SelectedItems.Count > 1)
                {
                    //save to a different directory
                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        string targetDir = fbd.SelectedPath;
                        foreach (ListViewItem lvi in lvPhotos.Items)
                        {
                            PhotoInfo pi = lvi.Tag as PhotoInfo;
                            string fileName = System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(pi.FullFileName));
                            pi.SaveAs(fileName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void lvPhotos_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                //open selected photo
                if (lvPhotos.SelectedItems.Count == 1)
                {
                    PhotoInfo pi = lvPhotos.SelectedItems[0].Tag as PhotoInfo;
                    System.Diagnostics.Process.Start(pi.FullFileName);
                }
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void mnuRemove_Click(object sender, EventArgs e)
        {
            try
            {
                List<ListViewItem> removeItems = new List<ListViewItem>();
                foreach (ListViewItem lvi in lvPhotos.SelectedItems)
                {
                    removeItems.Add(lvi);
                    PhotoInfo pi = lvi.Tag as PhotoInfo;
                    trackControl.Photos.Remove(pi);
                }
                foreach (ListViewItem lvr in removeItems)
                {
                    lvPhotos.Items.Remove(lvr);
                }
                lvPhotos.Refresh();
                trackControl.Draw();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void mnuShowOnMap_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (ListViewItem lvi in lvPhotos.SelectedItems)
                {
                    PhotoInfo pi = lvi.Tag as PhotoInfo;
                    pi.ShowOnMap = true;
                }
                trackControl.Draw();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void mnuHideOnMap_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (ListViewItem lvi in lvPhotos.SelectedItems)
                {
                    PhotoInfo pi = lvi.Tag as PhotoInfo;
                    pi.ShowOnMap = false;
                }
                trackControl.Draw();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void contextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                //select items
                int n = lvPhotos.SelectedItems.Count;
                if (n == 0)
                {
                    e.Cancel = true;
                    return;
                }

                if (n > 1)
                {
                    ctxHideOnMap.Visible = false;
                    ctxShowOnMap.Visible = false;
                }
                else // n=1
                {
                    PhotoInfo pi = lvPhotos.SelectedItems[0].Tag as PhotoInfo;
                    if (pi.ShowOnMap)
                    {
                        ctxShowOnMap.Visible = false;
                        ctxHideOnMap.Visible = true;
                    }
                    else
                    {
                        ctxShowOnMap.Visible = true;
                        ctxHideOnMap.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }
        #endregion Photos

        private void btnAxes_Click(object sender, EventArgs e)
        {
            try
            {
                if (_EditAxesDialog == null)
                {
                    _EditAxesDialog = new EditAxesDialog();
                    _EditAxesDialog.UseEqualScale = _UseEqualScale;
                    _EditAxesDialog.Zoom = _Zoom;
                    _EditAxesDialog.UseMap = _UseMap;
                    _EditAxesDialog.XCategory = _XCategory;
                    _EditAxesDialog.YCategory = _YCategory;
                    _EditAxesDialog.ShowMap = _ShowMap;
                    _EditAxesDialog.MapType = _MapType;
                    _EditAxesDialog.LastPointMaximum = _ActiveTrackSegment.WayPoints.Count;
                    _EditAxesDialog.ShowAllPointsOfSegment = _ShowAllPointsOfSegment;
                    _EditAxesDialog.IndexOfFirstPointShown = _IndexOfFirstPointShown;
                    _EditAxesDialog.IndexOfLastPointShown = _IndexOfLastPointShown;
                    _EditAxesDialog.CacheDate = _CacheDate;
                    _EditAxesDialog.RedrawRequested += new EventHandler(EditAxesDialog_RedrawRequested);
                    _EditAxesDialog.FormClosed += new FormClosedEventHandler(EditAxesDialog_FormClosed);
                }

                _EditAxesDialog.WindowState = FormWindowState.Normal;
                _EditAxesDialog.Show();
                _EditAxesDialog.BringToFront();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        void EditAxesDialog_FormClosed(object sender, FormClosedEventArgs e)
        {
            _EditAxesDialog.RedrawRequested -= new EventHandler(EditAxesDialog_RedrawRequested);
            _EditAxesDialog = null;
        }

        void EditAxesDialog_RedrawRequested(object sender, EventArgs e)
        {
            try
            {
                _UseEqualScale = _EditAxesDialog.UseEqualScale;
                _Zoom = _EditAxesDialog.Zoom;
                _UseMap = _EditAxesDialog.UseMap;
                _XCategory = _EditAxesDialog.XCategory;
                _YCategory = _EditAxesDialog.YCategory;
                _ShowMap = _EditAxesDialog.ShowMap;
                _MapType = _EditAxesDialog.MapType;
                _ShowAllPointsOfSegment = _EditAxesDialog.ShowAllPointsOfSegment;
                _IndexOfFirstPointShown = _EditAxesDialog.IndexOfFirstPointShown;
                _IndexOfLastPointShown = _EditAxesDialog.IndexOfLastPointShown;
                DateTime cacheDateNew = _EditAxesDialog.CacheDate;
                if (cacheDateNew > _CacheDate)
                {
                    //clear map tiles from memory
                    trackControl.ClearTilesCache();
                }
                _CacheDate = cacheDateNew;

                btnDraw.PerformClick();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            try
            {
                if (_EditViewDialog == null)
                {
                    _EditViewDialog = new EditViewDialog();
                    _EditViewDialog.DrawPhotos = _DrawPhotos;
                    _EditViewDialog.DrawPointsOfInterest = _DrawPointsOfInterest;
                    _EditViewDialog.DrawTrackLine = _DrawTrackLine;
                    _EditViewDialog.DrawWaypoints = _DrawWaypoints;
                    _EditViewDialog.StyleForPoI = _StyleForPoI;
                    _EditViewDialog.StyleForWaypoints = _StyleForWaypoints;
                    _EditViewDialog.TrackThickness = _TrackThickness;
                    _EditViewDialog.PhotoSize = _PhotoSize;
                    _EditViewDialog.WayPointsColor = _WayPointsColor;
                    _EditViewDialog.WayPointsHighlight = _WayPointsHighlight;
                    _EditViewDialog.PoIColor = _PoIColor;
                    _EditViewDialog.TrackColor = _TrackColor;
                    _EditViewDialog.TrackColorHighlight = _TrackColorHighlight;
                    _EditViewDialog.RedrawRequested += new EventHandler(EditViewDialog_RedrawRequested);
                    _EditViewDialog.FormClosed += new FormClosedEventHandler(EditViewDialog_FormClosed);
                }

                _EditViewDialog.WindowState = FormWindowState.Normal;
                _EditViewDialog.Show();
                _EditViewDialog.BringToFront();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        void EditViewDialog_FormClosed(object sender, FormClosedEventArgs e)
        {
            _EditViewDialog.RedrawRequested -= new EventHandler(EditViewDialog_RedrawRequested);
            _EditViewDialog = null;
        }

        void EditViewDialog_RedrawRequested(object sender, EventArgs e)
        {
            try
            {
                _DrawPhotos = _EditViewDialog.DrawPhotos;
                _DrawPointsOfInterest = _EditViewDialog.DrawPointsOfInterest;
                _DrawTrackLine = _EditViewDialog.DrawTrackLine;
                _DrawWaypoints = _EditViewDialog.DrawWaypoints;
                _StyleForPoI = _EditViewDialog.StyleForPoI;
                _StyleForWaypoints = _EditViewDialog.StyleForWaypoints;
                _TrackThickness = _EditViewDialog.TrackThickness;
                _PhotoSize = _EditViewDialog.PhotoSize;
                _WayPointsColor = _EditViewDialog.WayPointsColor;
                _WayPointsHighlight = _EditViewDialog.WayPointsHighlight;
                _PoIColor = _EditViewDialog.PoIColor;
                _TrackColor = _EditViewDialog.TrackColor;
                _TrackColorHighlight = _EditViewDialog.TrackColorHighlight;

                btnDraw.PerformClick();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void MapForm_ResizeBegin(object sender, EventArgs e)
        {
            try
            {
                _LastSplitterPosition = splitContainer1.SplitterDistance;
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void splitContainer1_Resize(object sender, EventArgs e)
        {
            try
            {
                splitContainer1.SplitterDistance = _LastSplitterPosition;
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }

        private void btnCompress_Click(object sender, EventArgs e)
        {
            try
            {
                CompressionParamsDialog cpd = new CompressionParamsDialog(_ActiveTrackSegment);
                cpd.ShowDialog();
            }
            catch (Exception ex)
            {
                Utils.HandleException(ex);
            }
        }
    }
}
